//microcommand define tofile
var fsp = require("fs/promises")
var { fileURLToPath, pathToFileURL } = require("url")
inject({ optional: ["ffmpeg", "silk"] })
signature("<file:fragment>", { checkArgCount: true })
option("name", "-n <string>")
action(async ({ session, options }, elements) => {
  const media = h.select(elements, "img,image,video,audio,record").filter(({ attrs: a }) => a.src || /[/\\]/.test(a.path))
  if (!media.length) return session.i18n(".no-input")
  let { type, attrs } = media[0]
  let { src, path } = attrs
  if (!/[/\\]/.test(path)) path = undefined
  let fallbackName = attrs.title || attrs.file_name || attrs.file || "download"

  let data
  silk2wav: if (["audio", "record"].includes(type) && (path || src.startsWith("file:")) && ctx.silk && ctx.ffmpeg) {
    let buf = await fsp.readFile(path || fileURLToPath(src))
    if (!ctx.silk.isSilk(buf)) break silk2wav
    buf = (await ctx.silk.decode(buf, 48000)).data
    data = await ctx.ffmpeg.builder().inputOption("-ar", "48000", "-f", "s16le").input(Buffer.from(buf)).outputOption("-c", "copy", "-f", "wav").run("buffer")
    fallbackName += ".wav"
  }

  if (!data) {
    if (path) src = pathToFileURL(path).href
    if (src.startsWith("data:wav;")) src = src.replace("wav", "audio/wav")
  }

  attrs = { title: fallbackName, file_name: fallbackName, file: fallbackName, ...attrs }
  delete attrs.path
  if (options.name) attrs.title = attrs.file_name = options.name
  if (!data) attrs.src = src

  if (data) return h.file(data, attrs)
  return h("file", attrs)
})
locale("zh-CN", { description: "将多媒体消息转换为文件", arguments: { file: "图片、视频或语音" }, messages: { "no-input": "未输入媒体文件…" } })